package tech.wisefin.track.session;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import tech.wisefin.track.TrackConfiguration;

import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api")
public class SessionTrackController {

    final SessionTrackService service;

    final TrackConfiguration config;

    public SessionTrackController(SessionTrackService service, TrackConfiguration config) {
        this.service = service;
        this.config = config;
    }

    @GetMapping(value = "/tracks")
    public Iterable<SessionTrackView> tracks() {
        return service.getSessionTrack();
    }

    @PostMapping(value = "/tracks/{session}")
    public RecordingForm record(
            @PathVariable String session,
            @RequestBody SessionTrackFragment fragment,
            @RequestParam("width") int width,
            @RequestParam("height") int height) {
        fragment.setWidth(width);
        fragment.setHeight(height);
        return this.record(session, fragment);
    }

    public RecordingForm record(String session, SessionTrackFragment fragment) {
        SessionTrack track = service.track(session, fragment);
        int fragmentCount = track.getFragments().size();
        return new RecordingForm(session, fragmentCount);
    }

    @GetMapping(value = "/replay/{session}")
    public ReplayForm replay(@PathVariable String session) {
        SessionTrack track = service.getSessionTrack(session)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到追踪数据"));
        return track.createReplay(this.config);
    }

    @PostMapping(value = "/replay/{session}")
    public void upload(@PathVariable String session,
                         @RequestPart("file") MultipartFile file) throws IOException {
        SessionTrack track = service.getSessionTrack(session)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "未找到数据"));

        String fileName = session + ".webm";
        File video = new File(config.getVideoLocalPath(), fileName);

        log.info("视频文件将上传至" + video.getAbsolutePath());
        file.transferTo(video);

        service.attach(track, video);
    }
}
